package com.xm.apd.nettyclient.netty;

import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

/**
 * Created by XMclassmate on 2017/12/18.
 */

public class Client {

    private static int port = 9998;

    public static void connect(String host) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new WriteTimeoutHandler(10));
                    ch.pipeline().addLast(new IdleStateHandler(0,0,5*60, TimeUnit.SECONDS));
                    ch.pipeline().addLast(new MessageEncoder());
                    ch.pipeline().addLast(new MessgeDecoder());
                    ch.pipeline().addLast(new ClientMsgHandler());
                }
            });
            ChannelFuture c = bootstrap.connect(host, port).sync();
            c.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            workerGroup.shutdownGracefully();
        }
    }
}
